package org.apache.seata.consumer;

/**
 * @author majinhui
 * @description
 * @create 2024/9/6 11:50
 **/

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.apache.seata.entity.Order;
import org.apache.seata.entity.Stock;
import org.apache.seata.mapper.OrderMapper;
import org.apache.seata.mapper.StockMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = {"rk_order_dlx_queue"})
public class DelayMsgConsumer {

    @Value("${rk.dlx.queue}")
    private String dlxQueue;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockMapper stockMapper;

    @RabbitHandler
    public void cancelOrder(Message message, Order order, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        orderMapper.delete(new QueryWrapper<Order>().eq("commodity_code", order.getCommodityCo()));
        Stock stockInfo = stockMapper.selectOne(new QueryWrapper<Stock>().eq("commodity_code", order.getCommodityCo()));
        Integer stockCount = stockInfo.getCount() + order.getCount();
        stockInfo.setCount(stockCount);
        //更新还原库存
        stockMapper.updateById(stockInfo);
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
